package dk.ahp.galgelegapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;

public class GalgeApplication extends Application {
	private static Galgelogik galgeLogik;
	public static ArrayList<String> muligeOrd;
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d("GalgeApplication", "onCreate");
		muligeOrd = new ArrayList<String>();
		updateWordList();
	}
	
	public static Galgelogik getGalgeLogik()
	{
		if (null ==galgeLogik){
			galgeLogik = new Galgelogik();
		}
		return galgeLogik;
	}
	
	public void updateWordList() {
		fetchWords("http://l-a.dk");
	}
	
	private void fetchWords(final String wordurl){
		
		class AsyncTask1 extends AsyncTask {
			ArrayList<String> ordHentetFraWeb = new ArrayList<String>();

			@Override
			protected Object doInBackground(Object... arg0) {
				try {
					URL url = new URL(wordurl);
			    
					// Read all the text returned by the server
					BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
					String str;
					while ((str = in.readLine()) != null) {
						// str is one line of text; readLine() strips the newline character(s)
						String[] tmp = str.substring(0, str.length()).split(" ");
						for (String s : tmp) {
							ordHentetFraWeb.add(s);
						}
					}
					in.close();

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					Log.d("AsyncTask", e.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Log.d("AsyncTask", e.toString());
				}
				Log.d("AsyncTask", "done");
				return null;
			}

			@Override
			protected void onPostExecute(Object result) {
				Log.d("AsyncTask", "onPostExecute");
				galgeLogik.muligeOrd = ordHentetFraWeb;
			}
		};
		new AsyncTask1().execute();
	}
}
